const BASE_URL = "http://127.0.0.1:8088"
//const BASE_URL = ""

class Api {
    private baseUrl: string;

    constructor(baseUrl: string) {
        this.baseUrl = baseUrl;
    }

    async request<T>(url: string, method: string, body?: any, headers?: HeadersInit): Promise<T> {
        let fullUrl = `${this.baseUrl}/${url}`;

        const requestHeaders: HeadersInit = new Headers(headers);
        requestHeaders.set("Content-Type", "application/json");

        const requestOptions: RequestInit = {
            method,
            headers: requestHeaders,
        };

        if (body) {
            if (method === "GET" || method === "DELETE") {
                const queryString = new URLSearchParams(body).toString();
                fullUrl = `${fullUrl}?${queryString}`;
            } else if (method === "POST" || method === "PUT") {
                requestOptions.body = JSON.stringify(body)
            }
        }

        const response = await fetch(fullUrl, requestOptions);
        if (!response.ok) {
            const message = await response.text();
            throw new Error(message);
        }

        const data: T = await response.json();
        return data;
    }

    async post<T>(url: string, body?: any, headers?: HeadersInit): Promise<T> {
        return this.request<T>(url, "POST", body, headers);
    }

    async put<T>(url: string, body?: any, headers?: HeadersInit): Promise<T> {
        return this.request<T>(url, "PUT", body, headers);
    }

    async get<T>(url: string, body?: any, headers?: HeadersInit): Promise<T> {
        return this.request<T>(url, "GET", body, headers);
    }

    async delete<T>(url: string, body?: any, headers?: HeadersInit): Promise<T> {
        return this.request<T>(url, "DELETE", body, headers);
    }
}

export const api = new Api(BASE_URL);



